import os
import subprocess
from .base import BaseNotifier
import logging

logger = logging.getLogger(__name__)

class MacOSNotifier(BaseNotifier):
    def __init__(self):
        super().__init__()  # 调用父类初始化
        self._check_notification_permission()

    def _check_notification_permission(self):
        """检查通知权限"""
        try:
            script = 'tell application "System Events" to get properties of current user'
            subprocess.run(['osascript', '-e', script], 
                         capture_output=True,
                         check=True)
        except subprocess.CalledProcessError:
            logger.warning(
                "未获得通知权限，请在系统设置中允许"
            )

    def _send_notification(self, title: str, message: str, timeout: int = 10):
        """MacOS 平台的通知实现"""
        try:
            # 转义特殊字符
            title = title.replace('"', '\\"')
            message = message.replace('"', '\\"')
            
            # 构建通知命令
            script = f'display notification "{message}" with title "{title}"'
            if self.config.NOTIFICATION_SOUND:
                script += ' sound name "default"'
            
            result = subprocess.run(
                ['osascript', '-e', script],
                capture_output=True,
                text=True,
                check=True
            )
            
            if result.stderr:
                logger.error(f"通知发送失败: {result.stderr}")
                
        except Exception as e:
            logger.error(f"发送通知错误: {e}")

    def test_notification(self):
        """测试通知是否正常工作"""
        try:
            script = 'display notification "测试通知内容" with title "测试通知"'
            result = subprocess.run(
                ['osascript', '-e', script],
                capture_output=True,
                text=True
            )
            
            if result.returncode == 0:
                logger.info("通知测试成功")
                return True
            else:
                logger.error(f"通知测试失败: {result.stderr}")
                return False
                
        except Exception as e:
            logger.error(f"通知测试异常: {e}")
            return False 